package itsm.isperp.module.controller.api.mobile;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.FileUploadInfo;
import itsm.isperp.framework.domain.UploadInfo;
import itsm.isperp.framework.service.UploadFileService;
import itsm.isperp.framework.upload.FilePersister;
import itsm.isperp.framework.utils.FileUploadParser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.service.app.AppMessageSuccessService;
import itsm.isperp.module.service.app.AppUserService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fr.stable.StringUtils;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-7-24
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/mobile/user")
public class MobileUserController {

	@Autowired
	public AppUserService appUserService;

	public static final Logger logger = LoggerFactory
			.getLogger(MobileSystemController.class);

	@RequestMapping("listContact")
	@ResponseBody
	public ResultMessage listContact() {
		try {
			JqGridRequest req = new JqGridRequest();
			req.setSelectColumns("a.id,a.name,photo,fullname,gender,b.name AS app_department_name,position,mobile");
			req.setPageable(false);
			req.setSearchString(" b.treenode_name_path NOT LIKE '%客户%'");
			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(appUserService.findAllDetailByRequest(req)));
		} catch (Exception ex) {
			return ResultMessage.failure(ex.getMessage());
		}

	}

	/**
	 * 获取MesssageCount
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping("messageCount")
	@ResponseBody
	public ResultMessage messageCount(String username) {

		try {
			// to do
			// 获取消息
			if (StringUtils.isNotEmpty(username)) {
				Map<String, Object> map = new HashMap<>();

				AppMessageSuccessService appMessageSuccessService = ContextHolder
						.getSpringBean("appMessageSuccessService");
				map.put("message_count", appMessageSuccessService
						.findMyMessageCount(username, false));

				return ResultMessage.success(map);
			} else {
				return ResultMessage.failure("用户名不能为空!");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("系统无法获消息总数,原因是:" + e.getMessage());
		}

	}

	/**
	 * 获取已办事项列表
	 * 
	 * @param username
	 *            用户名
	 * @param currentPage
	 * 
	 * @param pageSize
	 *            加载数量（默认20）
	 * @return
	 */
	@RequestMapping("listMessage")
	@ResponseBody
	public ResultMessage listMessage(String username, Integer currentPage,
			Integer pageSize) {

		try {
			// to do
			JqGridRequest request = new JqGridRequest();
			request.setPageable(true);
			request.setPage(currentPage);
			request.addFilterRule("receiver_id", JqGridFilterRuleOp.eq,
					username);
			request.setRows(pageSize);
			request.setSort("create_date", Direction.DESC);

			// 获取消息
			AppMessageSuccessService appMessageSuccessService = ContextHolder
					.getSpringBean("appMessageSuccessService");

			List<Map<String, Object>> list = appMessageSuccessService
					.findAllDetailByRequest(request).toPage().getContent();

			return ResultMessage.success(JsonBuilder.buildNormalBinder()
					.toJson(list));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取消息列表失败，原因是：" + e.getMessage());
		}

	}

	/**
	 * 标记消息已读
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("markReadMessage")
	@ResponseBody
	public ResultMessage markReadMessage(String id) {

		try {
			// to do
			// 获取消息
			AppMessageSuccessService appMessageSuccessService = ContextHolder
					.getSpringBean("appMessageSuccessService");
			appMessageSuccessService.markReadMessage(id);
			return ResultMessage.success();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("消息读取失败,原因是:" + e.getMessage());
		}

	}

	@RequestMapping("deleteMessage")
	@ResponseBody
	public ResultMessage deleteMessage(String id) {

		try {
			AppMessageSuccessService appMessageSuccessService = ContextHolder
					.getSpringBean("appMessageSuccessService");
			appMessageSuccessService.delete(id);
			return ResultMessage.success();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("删除失败,原因是:" + e.getMessage());
		}
	}

	@RequestMapping("betchDeleteMessage")
	@ResponseBody
	public ResultMessage betchDeleteMessage(String ids) {

		try {
			AppMessageSuccessService appMessageSuccessService = ContextHolder
					.getSpringBean("appMessageSuccessService");

			String[] idArr = ids.split(";");

			for (String id : idArr) {
				if (StringUtils.isNotEmpty(id)) {

					appMessageSuccessService.delete(id);

				}
			}
			return ResultMessage.success();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("删除失败,原因是:" + e.getMessage());
		}
	}

	/**
	 * 根据用户名获取用户信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("getUserInfo")
	@ResponseBody
	public ResultMessage getUserInfo(String username) {

		try {
			// to do
			// 获取消息
			AppUserService appUserService = ContextHolder
					.getSpringBean("appUserService");
			if (StringUtils.isNotEmpty(username)) {
				AppUser appUser = appUserService.findByUsername(username);
				if (appUser != null) {
					return ResultMessage.success(JsonBuilder
							.buildNormalBinder().toJson(appUser));
				} else {
					return ResultMessage.failure("获取用户信息失败，用户不存在！");
				}
			} else {
				return ResultMessage.failure("获取用户信息失败，用户名为空！");
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("获取用户信息失败,原因是:" + e.getMessage());
		}

	}

	/**
	 * 修改用户密码
	 * 
	 * @param username
	 * @param oldpassword
	 * @param newpassword
	 * @return
	 */
	@RequestMapping("updateUserPwd")
	@ResponseBody
	public ResultMessage updateUserPwd(String username, String oldpassword,
			String newpassword) {

		try {
			// to do
			// 获取消息
			AppUserService appUserService = ContextHolder
					.getSpringBean("appUserService");
			if (StringUtils.isNotEmpty(username)) {
				AppUser appUser = appUserService.findByUsername(username);
				if (appUser != null) {
					appUserService.changePassword(appUser, oldpassword,
							newpassword);
				}

			}

			return ResultMessage.success("更新用户密码成功！");

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("更新用户密码失败,原因是:" + e.getMessage());
		}

	}

	/**
	 * 上传头像
	 * 
	 * @param username
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "uploadUserPhoto")
	public ResultMessage uploadUserPhoto(HttpServletRequest req,
			HttpServletResponse resp) throws UnsupportedEncodingException {

		try {

			req.setCharacterEncoding("UTF-8");
			resp.setCharacterEncoding("UTF-8");

			String username = req.getParameter("username");
			AppUserService appUserService = ContextHolder
					.getSpringBean("appUserService");
			if (StringUtils.isNotEmpty(username)) {
				AppUser appUser = appUserService.findByUsername(username);
				if (appUser != null) {

					UploadFileService<UploadInfo> uploadFileService = ContextHolder
							.getSpringBean("appUploadFileService");
					FilePersister filePersister = ContextHolder
							.getSpringBean("isperp.filePersister");

					FileUploadParser parser = new FileUploadParser();
					FileUploadInfo fileUploadInfo = parser.parse(req);
					String sourceId = appUser.getId();

					UploadInfo uploadInfo = ContextHolder
							.getSpringBean("isperp.uploadInfo");

					FileItem fileItem = fileUploadInfo.getFileItems().get(0);
					if (fileItem.getContentType() != null) {// 如果是文件类型

						uploadInfo.setId(HibernateUUIDGenerator.generate());
						uploadInfo.setSourceId(sourceId);
						fileUploadInfo.parseUploadInfo(fileItem.getName(),
								uploadInfo);

						// //将文件进行保存到目录在持久化操作
						try {
							filePersister.persist(fileItem.getInputStream(),
									uploadInfo);
						} catch (IOException e) {
							return ResultMessage.failure(e.getMessage());
						}
						if (StringUtils.isNotEmpty(sourceId)) {
							uploadInfo.setModifyDate(new Timestamp(new Date()
									.getTime()));
							uploadInfo.setModifier(username);
							uploadInfo.setCreator(username);
							uploadFileService.saveOrUpdate(uploadInfo);

							appUser.setPhoto(uploadInfo.getPath());
							appUserService.saveOrUpdate(appUser);

						}

						return ResultMessage.success(uploadInfo);

					}

				}
			}

			return ResultMessage.failure();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultMessage.failure("上传头像失败,原因是:" + e.getMessage());
		}

	}

}
